/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.sumgr.core;

import io.iec.edp.caf.commons.runtime.FileOperator;
import io.iec.edp.caf.commons.runtime.msu.MsuConfigVariable;
import io.iec.edp.caf.commons.runtime.msu.entities.ServiceUnitYaml;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.sumgr.api.ServiceUnitGenerator;
import io.iec.edp.caf.sumgr.api.entity.ServiceUnitInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * SU描述文件生成器
 *
 * @author wangyandong
 * @date 2021/04/09 10:11
 */
@Deprecated
public class ServiceUnitGeneratorImpl implements ServiceUnitGenerator {
    private static final String FILE_NAME="ServiceUnit.json";

    private static final String JSON_FORMAT=
            "{\n" +
            "    \"ServiceUnitInfo\" :\n" +
            "    {\n" +
            "        \"ApplicationName\" : \"%s\",\n" +
            "        \"ServiceUnitName\" : \"%s\",\n" +
            "        \"Type\" : \"%s\"\n" +
            "    }\n" +
            "}";
    private static final Logger logger = LoggerFactory.getLogger(ServiceUnitGeneratorImpl.class);

    /**
     * whether ServiceUnit.json exists
     * @param destDir   The directory for the root of the package hierarchy
     *                          for generated files.
     */
    public Boolean exists(File destDir){
        if(destDir==null || !destDir.isDirectory())
            throw new IllegalArgumentException("destDir is null or invalidate");

        File[] files = destDir.listFiles((dir, name) -> {
            File file1 = new File(dir, name);
            return file1.isFile() && name != null && (MsuConfigVariable.SU_JSON_FILE.equalsIgnoreCase(name)
                    ||MsuConfigVariable.SU_YAML_FILE.equalsIgnoreCase(name)||MsuConfigVariable.SU_YML_FILE.equalsIgnoreCase(name));
        });

        //识别为su目录
        return  (files != null && files.length > 0);
    }

    /**
     * Generate service-unit.yaml.
     * @param msuYamlInfo msu information
     * @param destDir The directory for the root of the package hierarchy
     *                         for generated files. Can not be null.
     */
    @Override
    public void generate(ServiceUnitYaml msuYamlInfo, File destDir) {
        if(msuYamlInfo==null || msuYamlInfo.resolveName()==null || msuYamlInfo.resolveApplicationName()==null)
            throw new IllegalArgumentException("ServiceUnitInfo is null or contains empty parameter");

        if(destDir==null || destDir.isDirectory()==false)
            throw new IllegalArgumentException("destDir is null or invalidate");

        File file = new File(destDir, MsuConfigVariable.SU_YAML_FILE);
        if (file.exists()) {
            logger.error("Service-unit.yaml already exists at "+destDir);
            return;
        }
        try {
            //创建文件
            file.createNewFile();

            String data = FileOperator.toYaml(msuYamlInfo);
            try (FileWriter fileWritter = new FileWriter(file, true);
                 BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            ) {
                bufferWritter.write(data);
                bufferWritter.flush();
            }
        }catch(IOException e) {
            logger.error(e.getMessage(),e);
        }
        //将su注册至本地服务中
        try{
            List<io.iec.edp.caf.msu.api.entity.ServiceUnitInfo> infos = new ArrayList<>();
            io.iec.edp.caf.msu.api.entity.ServiceUnitInfo info = new io.iec.edp.caf.msu.api.entity.ServiceUnitInfo(msuYamlInfo.resolveMsuCommonInfo());
            info.setPath(destDir.getAbsolutePath());
            infos.add(info);
            ServiceUnitAwareService suAwareSvc = SpringBeanUtils.getBean(ServiceUnitAwareService.class);
            assert suAwareSvc != null;
            suAwareSvc.registerServiceUnitsInfo(infos);
        }catch (Throwable e){
            throw new RuntimeException("Could not register Msu",e);
        }
    }

    /**
     * Generate ServiceUnit.json.
     * @param destDir   The directory for the root of the package hierarchy
     *                          for generated files. Can not be null.
     */
    @Override
    public void generate(ServiceUnitInfo info, File destDir) {
        if(info==null || info.getName()==null || info.getApplicationName()==null)
            throw new IllegalArgumentException("ServiceUnitInfo is null or contains empty parameter");

        ServiceUnitYaml serviceUnitYaml = info.convertToYaml();
        generate(serviceUnitYaml,destDir);
    }

}
